package com.wobito.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wobito.common.constants.BusinessException;
import com.wobito.common.constants.ErrorCode;
import com.wobito.common.utils.DateUtils;
import com.wobito.mapper.BorrowMapper;
import com.wobito.pojo.bean.Borrow;
import com.wobito.pojo.bean.ConfigType;
import com.wobito.pojo.bean.Person;
import com.wobito.pojo.dto.api.GetBorrowByPersonIdDTO;
import com.wobito.pojo.dto.api.GetBorrowDTO;
import com.wobito.pojo.dto.borrow.BorrowByPersonDTO;
import com.wobito.pojo.dto.borrow.BorrowDTO;
import com.wobito.pojo.dto.borrow.BorrowReminderDTO;
import com.wobito.pojo.enums.BorrowStatusEnum;
import com.wobito.pojo.result.ReminderResult;
import com.wobito.pojo.vo.borrow.BorrowVO;
import com.wobito.service.IBorrowService;
import com.wobito.service.IConfigTypeService;
import com.wobito.service.IPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lambyang
 * @since 2024-08-29
 */
@Service
public class BorrowServiceImpl extends ServiceImpl<BorrowMapper, Borrow> implements IBorrowService {

    private Date getMaxExpiredDay(Date time){
        ConfigType configType=configTypeService.getOne(new LambdaQueryWrapper<ConfigType>().eq(ConfigType::getConfigKey,"expired:reminder:time"));
        return DateUtils.reduceDate(time,Integer.valueOf(configType.getConfigValue()));
    }

    @Autowired
    private BorrowMapper borrowMapper;
    @Autowired
    private IConfigTypeService configTypeService;
    @Autowired
    private IPersonService personService;

    @Override
    public List<BorrowByPersonDTO> selectBorrowByPerson(Long personId) {
        return borrowMapper.selectBorrowByPerson(personId);
    }

    @Override
    public List<GetBorrowByPersonIdDTO> selectBorrowByICCode(String IcCode) {
        Person person=personService.getOne(new LambdaQueryWrapper<Person>().eq(Person::getIcCode,IcCode));
        if (ObjectUtil.isNull(person)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"未找到该用户!");
        }
        return borrowMapper.selectBorrowByPersonId(person.getId());
    }

    @Override
    public List<BorrowDTO> selectBorrowList(BorrowVO borrowVO) {
        return borrowMapper.selectBorrowList(borrowVO);
    }

    @Override
    public List<GetBorrowDTO> selectBorrowApi(Long personId, Long bookId) {
        return borrowMapper.selectBorrowApi(personId,bookId);
    }

    @Override
    public List<ReminderResult> selectBorrowReminderList(Long id) {
        List<ReminderResult> reminderResults = new ArrayList<>();
        List<BorrowReminderDTO> borrowReminderDTOS = borrowMapper.selectBorrowByPersonReminder(id);
        if (CollectionUtil.isNotEmpty(borrowReminderDTOS)) {
            //逾期
            List<BorrowReminderDTO> overTimes = borrowReminderDTOS.stream().filter(b -> b.getStatus().equals(BorrowStatusEnum.OVERDUE)).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(overTimes)) {
                overTimes = overTimes.stream().sorted(Comparator.comparing(BorrowReminderDTO::getDueTime).reversed()).collect(Collectors.toList());
                for (BorrowReminderDTO over : overTimes) {
                    ReminderResult result = BeanUtil.copyProperties(over, ReminderResult.class);
                    result.setStatus(BorrowStatusEnum.OVERDUE.getName());
                    result.setTime(over.getRenewTime());
                    result.setDay(DateUtils.getDatePoor(over.getRenewTime()!=null?over.getRenewTime():over.getDueTime(), DateUtils.getNowDate()));
                    reminderResults.add(result);
                }
            }
            //临期
            List<BorrowReminderDTO> adventTimes = borrowReminderDTOS.stream().filter(b -> !b.getStatus().equals(BorrowStatusEnum.OVERDUE)).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(adventTimes)) {
                adventTimes = adventTimes.stream().sorted(Comparator.comparing(BorrowReminderDTO::getDueTime).reversed()).collect(Collectors.toList());
                for (BorrowReminderDTO advent : adventTimes) {
                    //判断是否临期小于设置参数
                    Date time=advent.getRenewTime()!=null?advent.getRenewTime():advent.getDueTime();
                    if (DateUtils.isTimeBefore(DateUtils.getNowDate(),getMaxExpiredDay(time))){
                        continue;
                    }
                    ReminderResult result = BeanUtil.copyProperties(advent, ReminderResult.class);
                    result.setStatus("即将到期");
                    result.setTime(advent.getDueTime() != null ? advent.getDueTime() : advent.getRenewTime());
                    result.setDay(DateUtils.getDatePoor(advent.getDueTime() != null ? advent.getDueTime() : advent.getRenewTime(), DateUtils.getNowDate()));
                    reminderResults.add(result);
                }
            }
        }
        return reminderResults;
    }
}
